이벤트

✒️ 2025-06-23 11:50 내용 수정


웹 브라우저가 알려주는 HTML 요소에 대한 사건의 발생

이벤트 객체(event object)


마우스 이벤트

이벤트 설명
click 요소를 클릭했을 때 발생
dbclick 요소를 더블 클릭했을 때 발생
mouseover 마우스가 요소에 들어올 때(오버할 때) 발생
mouseout 마우스가 요소에서 나갈 때(아웃할 때) 발생
mousemove 마우스가 요소 위에서 움직일 때 발생
mousedown 마우스를 눌렀을 때 발생
mouseup 마우스를 떼었을 때 발생
contextmenu context menu(마우스 우클릭 메뉴)가 나오기 전에 발생
<table border="1px">
	<tr>
		<th>수1</th>
		<td><input id="num1" placeholder="정수만 입력하세요"></td>
	</tr>
	<tr>
		<th>수2</th>
		<td><input id="num2" placeholder="정수만 입력하세요"></td>
	</tr>
	<tr>
		<td colspan="2">
			<ul>
				<li><input type="button" value="+" onclick="calc('+')"></li>
				<li><input type="button" value="-" onclick="calc('-')"></li>
				<li><input type="button" value="*" onclick="calc('*')"></li>
				<li><input type="button" value="/" onclick="calc('/')"></li>
			</ul>
		</td>
	</tr>
	<tr>
		<th>결과</th>
		<td id="result"></td>
	</tr>
</table>

<script>
	function calc(n) {
		let num1 = Number(document.getElementById('num1').value);
		let num2 = Number(document.getElementById('num2').value);
		let num3 = document.getElementById('result');
		
		if(isNaN(num1) || isNaN(num2)) {
			alert('숫자만 입력하세요.');
			return;	
		}

		switch(n) {
			case '+':
				result.innerHTML = num1+num2;
			break;
			case '-':
				result.innerHTML = num1-num2;
			break;
			case '*':
				result.innerHTML = num1*num2;
			break;
			case '/':
				result.innerHTML = num1/num2;
			break;
		}	
}
</script>

계산기1.png


키보드 이벤트

참고 자료 : mdn web docs keyboard event key values

이벤트 설명
keydown 키를 눌렀을 때 발생
keyup 키를 떼었을 때 발생
keypress 키를 누른 상태일 때 발생
키 이름 event.key 설명
문자 키 "a" ~ "z" 소문자 (Shift 키와 함께 누르면 대문자)
숫자 키 "0" ~ "9" 숫자 키 (상단 숫자열)
Enter "Enter" 엔터 키
Space " " 스페이스바 (공백 문자)
Backspace "Backspace" 백스페이스 키
Tab "Tab" 탭 키
Shift "Shift" Shift 키
Control "Control" Ctrl 키
Alt "Alt" Alt 키
Escape "Escape" Esc 키
Delete "Delete" Delete 키
화살표 키 "ArrowUp" 위쪽 화살표 키
"ArrowDown" 아래쪽 화살표 키
"ArrowLeft" 왼쪽 화살표 키
"ArrowRight" 오른쪽 화살표 키
Function 키 "F1" ~ "F12" 기능 키
Caps Lock "CapsLock" Caps Lock 키
Insert "Insert" Insert 키
Home "Home" Home 키
End "End" End 키
Page Up "PageUp" Page Up 키
Page Down "PageDown" Page Down 키
Num Lock "NumLock" Num Lock 키
Scroll Lock "ScrollLock" Scroll Lock 키
Print Screen "PrintScreen" Print Screen 키
Context Menu "ContextMenu" 컨텍스트 메뉴 키
Meta (윈도우/커맨드) "Meta" Windows 키 (Win) 또는 Command 키 (Mac)
식별 불가능한 키 "Unidentified" 키를 식별할 수 없는 경우
<input type="text" id="inputBox" placeholder="엔터를 눌러보세요">
<p id="result"></p>

<script>
	const inputBox = document.querySelector("#inputBox");
	const result = document.querySelector("#result");

	inputBox.addEventListener("keydown", (e) => {
		if (e.key === "Enter") {
			const content = inputBox.value.trim();
			if (content) {
				result.textContent = `입력값 : ${content}`;
				inputBox.value = '';
			}
		}
	});
</script>

js_keyboard_event.png


폼 이벤트

이벤트 설명
focus 요소에 포커스가 이동했을 때 발생
blur 요소에 포커스가 벗어났을 때 발생
change 요소 값이 변경 되었을 때 발생
submit type=submit 버튼을 눌렀을 때(폼을 제출) 발생
reset type=reset 버튼을 눌렀을 때 발생
select input이나 textarea 요소 안의 텍스트를 드래그해서 선택할 때 발생
input 입력 요소의 값이 변경됬을 때 발생
const form = document.getElementByTagName("form");

form.addEventListener("submit", (e) => {
	e.preventDefault(); // 자동 제출 방지
});
<script>
function validate(e) {
	// input 값 가져오기
	const num1 = document.getElementById("num1").value;
	const num2 = document.getElementById("num2").value;
	const errorMessage = document.getElementById("errorMessage");
	
	if (!num1 || !num2) {
		e.preventDefault(); // ✅ 입력이 없을 때만 막기
		errorMessage.textContent = "값을 입력해주세요";
		return false; // ❌ 제출 차단
	}
	return true; // ✅ 유효하면 제출 허용
}
</script>

<form action="/calculate" method="get" onsubmit="return validate(event)">  
    <input type="number" id="num1" name="num1">  
    <input type="number" id="num2" name="num2">  
    <select id="operator" name="operator">  
        <option value="+">+</option>  
        <option value="-">-</option>  
        <option value="*">*</option>  
        <option value="/">/</option>  
    </select>  
    <button type="submit">제출</button>  
</form>  
<p id="errorMessage">에러 메시지</p>  

예제

<form id="signup-form">
	<label>이름:<input type="text" id="name"></label><br>
	<label>이메일:<input type="email" id="email"></label><br>
	<button type="submit">제출</button>
</form>
<p id="output"></p>

<script>
	const form = document.querySelector("#signup-form");
	const output = document.querySelector("#output");
	const usernameInput = document.querySelector("#name");
	const emailInput = document.querySelector("#email");

	form.addEventListener("submit", (e) => {
		e.preventDefault();
		const name = usernameInput.value.trim();
		const email = emailInput.value.trim();
		if (name === "" || email === "") {
			output.textContent = "이름과 이메일을 입력해주세요";
			return;
		} 
		output.textContent = `이름: ${name}, 이메일: ${email}`;
	});
</script>

js_form_event 1.png

js_form_event 2.png


윈도우 이벤트

이벤트 설명
load 문서나 이미지 등이 로드될 때 발생
unload 문서가 언로드될 때 발생
resize 브라우저 창의 크기가 변경될 때 발생
scroll 문서나 요소가 스크롤될 때 발생
hashchange URL의 해시 부분이 변경될 때 발생
popstate 브라우저의 상태(뒤로가기, 앞으로가기 등)가 변경될 때 발생
abort 이미지 로딩이 중단될 때 발생
window.onload = function() {
	// 실행 내용
	// alert("페이지가 로드되었습니다.");
}

스크롤 이벤트 예시

body{
	height: 200vh;
}
div{
	height: 200vh;
}
#target {
	margin-top: 500px;
	padding: 20px;
	background-color: lightblue;
	border: 1px solid #333;
}
<button onclick="scrollToBottm()">Scroll Down</button>
<button onclick="scrollToTarget()">Scroll To Target</button>
<div>
	<div id="target">Taget box</div>
</div>
<button onclick="scrollToTop()">Top</button>

<script>
	// 맨 아래로 이동
	function scrollToBottm() {
		window.scrollTo({
			top: document.body.scrollHeight, behavior:'smooth'
		});
	}
	// 맨 위로 이동
	function scrollToTop() {
		window.scrollTo({top: 0, behavior: 'smooth'});
	}
	// 타겟 위치로 이동
	function scrollToTarget() {
		const target = document.getElementById('target');
		target.scrollIntoView({ behavior: 'smooth' });
	}
</script>

scroll_event.gif


애니메이션 이벤트

이벤트 설명
animationstart CSS 애니메이션이 시작될 때 발생
animationend CSS 애니메이션이 끝날 때 발생
animationiteration CSS 애니메이션이 반복될 때 발생

트랜지션 이벤트

이벤트 설명
transitionstart CSS 트랜지션이 시작될 때 발생
transitionend CSS 트랜지션이 끝날 때 발생

기타 이벤트

이벤트 설명
DOMContentLoaded 문서의 HTML이 완전히 로드되고 파싱된 후 발생
error JavaScript 코드에서 에러가 발생했을 때 발생
beforeunload 사용자가 페이지를 떠날 때(창을 닫거나 다른 페이지로 이동) 발생.
fullscreenchange 전체 화면 모드로 변경될 때 발생
fullscreenerror 전체 화면 모드로 진입을 실패했을 때 발생